package com.huilink.webmail.util.client;

import asquare.gwt.debug.client.Debug;
import asquare.gwt.debug.client.DebugElementDumpInspector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.user.client.Window;

public final class DebugUtils {
	
    private DebugUtils() {
        // hide constructor because we are a utility class with static methods only.
    }

    public static void initDebugAndErrorHandling() {
    	new DebugElementDumpInspector().install();
    	if(GWT.isScript()){
	        GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
	            public void onUncaughtException(final Throwable tracepoint) {
	                performDefaultErrorHandling(tracepoint);
	            }
	        });
    	}
    }

    public static void performDefaultErrorHandling(final Throwable caught) {
    	Debug.println(""+caught);
        if (caught != null) {
            final String stacktrace = DebugUtils.getStacktraceAsString(caught);
            Debug.println(stacktrace);
            Window.alert(stacktrace);
        } else {
            final String message = "Error ocuured, but we have no further information about the cause";
            Debug.println(message);
            Window.alert(message);
        }
    }

    public static String getStacktraceAsString(Throwable throwable) {
    	String text = "Uncaught exception: ";
    	Throwable e = throwable;
    	while (e != null) {
    		StackTraceElement[] stackTraceElements = e.getStackTrace();
    		text += new String(e.toString() + "\n"); 
    		for (int i = 0; i < stackTraceElements.length; i++) { 
    			text += "    at " + stackTraceElements[i] + "\n";
    		}         
    		e = e.getCause();       
    		if (e != null) {      
    			text += "Caused by: ";       
    		}
    	}
        return text;
        
    }


}
